package com.yxhl.zoume.data.http.rest.repositoryimpl.base;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.yxhl.zoume.data.DataConstants;
import com.yxhl.zoume.data.http.rest.ZouMeService;
import com.yxhl.zoume.data.retrofit.converter.protobuf.ZMProtoConverterFactory;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.protobuf.ProtoConverterFactory;

/**
 * 数据请求基类：
 * 初始化Retrofit，创建ZouMeService
 * <p>
 * Created by Xboy on 16/3/15.
 */
@Singleton
public class BaseDataRepository {

    // 请求超时时长
    private static final long TIMEOUT = 20000;

    // APIs
    protected final ZouMeService mZouMeService;

    public BaseDataRepository() {
        // 1.配置client
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .addNetworkInterceptor(new StethoInterceptor())
                .build();

        // 2.1配置gson
        // Creates the json object which will manage the information received
        GsonBuilder builder = new GsonBuilder();
        // Register an adapter to manage the date types as long values
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
        Gson gson = builder.serializeNulls().create();
        GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);

        //2.2配置Proto
        ProtoConverterFactory protoConverterFactory = ProtoConverterFactory.create();

        // 3.创建retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(DataConstants.BASE_URL)
                .addConverterFactory(ZMProtoConverterFactory.create())
//                .addConverterFactory(ProtoConverterFactory.create())
                .addConverterFactory(gsonConverterFactory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mZouMeService = retrofit.create(ZouMeService.class);
    }
}
